package com.gaogzhen.datastructure.queue;

import java.util.NoSuchElementException;

/**
 *  数组实现队列
 *  数组可以循环使用
 */
public class ArrayQueue<E> {
    private E[] element;
    private int size;
    private int start;
    private int end;
    private int capacity;

    private static final int DEFAULT_CAPACITY = 10;

    public ArrayQueue(int capacity) {

        this.capacity = capacity <= 0 ? DEFAULT_CAPACITY: capacity;
        element = (E[]) new Object[capacity];
    }

    public ArrayQueue() {
       this(DEFAULT_CAPACITY);
    }

    // 获取队列元素数量
    public int size() { return size;}

    // 队列是否已满
    public boolean isFull() { return (end + 1) % capacity == start;}

//    private boolean isEmpty() {
//        return (start + 1) % capacity == end;
//    }

    // 队列是否为空
    public boolean isEmpty() { return size == 0;}

    // 添加信息元素
    public void add(E e) {
        if (isFull()) {
            System.out.println("队列已满");
            return;
        }
        element[end] = e;
        end = (end + 1) % capacity;
        size++;
    }

    // 取最前面的元素，同时移除
    public E pop() {
        if (isEmpty())
            throw new RuntimeException("队列为空");
        E o = element[start];
        start = (start + 1) % capacity;
        size--;
        return o;
    }

    // 获取最前面的元素,不移除
    public E peek() {
        if (isEmpty())
            return null;
        return element[start];
    }
}
